package DesignPattern;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

public class SingleLazyPattern {
    private static boolean isCreate = false;

    private SingleLazyPattern() {
        if (!isCreate) {
            isCreate = true;
        }else{
            throw new RuntimeException("反射获取失败");
        }
        System.out.println(Thread.currentThread().getName().toString());
    }

    private volatile static SingleLazyPattern singleLazyPattern = null;

//    public synchronized static SingleLazyPattern getSingleLazyPatternInstance() {
//        if (singleLazyPattern == null) {
//            singleLazyPattern = new SingleLazyPattern();
//        }
//        return singleLazyPattern;
//    }

    //双重检测锁
    public static SingleLazyPattern getSingleLazyPatternInstance() {
        if (singleLazyPattern == null) {
            synchronized (SingleLazyPattern.class) {
                if (singleLazyPattern == null) {
                    singleLazyPattern = new SingleLazyPattern();
                }
            }
        }
        return singleLazyPattern;
    }

    public static void main(String[] args) throws Exception {
        //通过反射创建对象
        Constructor<SingleLazyPattern> declaredConstructor = SingleLazyPattern.class.getDeclaredConstructor(null);
        declaredConstructor.setAccessible(true);
        SingleLazyPattern singleLazyPattern = declaredConstructor.newInstance();
        System.out.println(singleLazyPattern);
        //通过反射破坏掉表示位创建对象
        Field isCreate = SingleLazyPattern.class.getDeclaredField("isCreate");
        isCreate.setAccessible(true);
        isCreate.set(singleLazyPattern,false);
        SingleLazyPattern singleLazyPattern1 = declaredConstructor.newInstance();
        System.out.println(singleLazyPattern1);

    }
}
